import Redis from 'ioredis';
import cluster from 'cluster';
import {getPublicPlatfromList,initActiveAccessTokens} from '../controllers/wx_token';
import {
    REDIS_CONN_IPTIONS,
    REDIS_AI_STORY_ALBUM_GROUP,
    REDIS_AI_STORY_PUBLIC_PLATFORM,
    WX_TOKEN_,
    MASTER_REDIS_WX_TOKEN_OPTIONS,
    SUB_WX_VOICE,
    SUB_WX_SUBSCRIBE
} from '../config/config';
import { sendLogToEmail } from '../controllers/logger';

if (cluster.isWorker) {
    Redis.Promise.onPossiblyUnhandledRejection(function (error) {
        console.error(`[worder][${cluster.worker.id}]:redis异常信息:`, error);
    });
    var cacheRedis = new Redis(REDIS_CONN_IPTIONS);
    cacheRedis.connect().then(function () {
        console.info(`[workder][${cluster.worker.id}]redis is running`);
    });
    var wxTokenRedis = new Redis(MASTER_REDIS_WX_TOKEN_OPTIONS);
    wxTokenRedis.connect().then(function () {
        console.info(`[workder-wxtoken][${cluster.worker.id}]:redis is running`);
    });
}


/**
* @param {访问token} accessToken 
 * @param {设备序列号} deviceSn 
 * @param {用户id} openidId 
 * @param {音频id} mediaId 
 *  * @param {0:表示新增记录,1:表示更新} status 
 */
export function sendNewVoice(accessToken, deviceSn, openId, mediaId,status) {
    wxTokenRedis.publish(SUB_WX_VOICE,JSON.stringify({access_token:accessToken,device_sn:deviceSn, open_id:openId,media_id:mediaId,status:status})).then(function(ret){
        console.log(`SUB_WX_VOICE:${ret}`);
    },function(err){
        console.log(`SUB_WX_VOICE error:`, err);
    })
}

/**
 * 关注公众号,绑定设备消息提示
 * @param {*} accessToken 
 * @param {*} openId 
 * @param {*} host 
 * @param {*} wechat_id 
 * @param {*} bindImgUrl 
 */
export function sendSubscribeMessage(accessToken, openId, host, wechat_id, bindImgUrl){
    wxTokenRedis.publish(SUB_WX_SUBSCRIBE,JSON.stringify({access_token:accessToken,open_id:openId,host:host, wechat_id:wechat_id, url:bindImgUrl})).then(function(ret){
        console.log(`SUB_WX_SUBSCRIBE:${ret}`);
    },function(err){
        console.log(`SUB_WX_SUBSCRIBE error:`, err);
    })
}


// 初始化加载首页数据
export function setAlbumGroup(album_group_template_id, permission_group_id, categoryList) {
    const key = REDIS_AI_STORY_ALBUM_GROUP + album_group_template_id + ':' + permission_group_id;
    const json = JSON.stringify(categoryList);
    return cacheRedis.set(key, json);
}


export function getAlbumGroup(album_group_template_id, permission_group_id) {
    const key = REDIS_AI_STORY_ALBUM_GROUP + album_group_template_id + ':' + permission_group_id;
    return cacheRedis.get(key);
}

// 缓存公众号配置信息
export function savePublicPlatfrom(publicPlatform) {
    const key = REDIS_AI_STORY_PUBLIC_PLATFORM + publicPlatform.wechat_id;
    const json = JSON.stringify(publicPlatform);
    return cacheRedis.set(key, json);
}

export function getPublicPlatfrom(wechat_id) {
    const key = REDIS_AI_STORY_PUBLIC_PLATFORM + wechat_id;
    return cacheRedis.get(key);
}


/**
 * 重新从redis中拉取最新的token
 */
export async function initWxTokenAgain(wokerId){
    let newWxTokenList = [];
    const list = getPublicPlatfromList();
    for (let index = 0; index < list.length; index++) {
        const item = list[index];
        if (item) {
            const wxTokenString = await wxTokenRedis.get(WX_TOKEN_+item.wechat_id);
            const json = JSON.parse(wxTokenString);
            newWxTokenList.push(json);
        }
    }
    console.log(`worker[${wokerId}],pull wxtoken,wxconfig;${list.length},wxcount:${newWxTokenList.length}`);
    initActiveAccessTokens(newWxTokenList);
}


/**
 * 清除所有redis中的key
 */
export function clearRedisData() {
    cacheRedis.flushall().then(function () {
        console.log(`已清除redis中所有的缓存数据`);
    }, function (err) {
        console.error(err);
        sendLogToEmail(err);
    });
}





